package cn.acewill.yxd.yunxundian.Api;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.pubClass.OKHttpUICallback;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.UpdateUtils;
import okhttp3.Call;

/**
 * Created by XXX on 2017/12/22.
 * apk版本更新下载请求
 */

public class UpdateApi {

    private static UpdateApi instance;
    private ProgressDialog progressDialog;
    private UpdateApi(){

    }
    public static UpdateApi getInstance(){
        if (instance==null){
            instance = new UpdateApi();
        }
        return instance;
    }

    public void downLoadApk(final Context mContext,String apkUrl,String saveUrl){
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("apk下载中，请耐心等待....");
        progressDialog.show();
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return keyCode == KeyEvent.KEYCODE_BACK;
            }
        });
        RequestParams requestParams = new RequestParams(apkUrl);
        requestParams.setSaveFilePath(saveUrl);
        requestParams.setAutoResume(true);
        requestParams.isCancelFast();
         x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }
            @Override
            public void onStarted() {
            }
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

                progressDialog.setProgress((int)current);
                progressDialog.setMax((int) total);
                float all=(float) Math.round(total)/1024/1024;
                float percent=(float) Math.round(current)/1024/1024;
                progressDialog.setProgressNumberFormat(String.format(Locale.getDefault(),"%.3fM/%.3fM",percent,all));
            }
            @Override
            public void onSuccess(File result) {
                progressDialog.dismiss();
                //打开文件
                Log.e("savePath",result.getPath());
                update(mContext,result.getPath());
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                BaseActivity.showAnimaDialog(mContext,"下载失败");
                progressDialog.dismiss();
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }

    private void update(Context context,String path){
        //安装应用
        File apkFile = new File(path);
        if (!apkFile.exists()){
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
//        //7.0文件访问权限被回收
//        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
//            intent.setDataAndType(Uri.fromFile(new File(path)),
//                     "application/vnd.android.package-archive");
//            context.startActivity(intent);
//        }else{
            intent.setDataAndType(Uri.fromFile(new File(path)),
                    "application/vnd.android.package-archive");
            context.startActivity(intent);

    }

}
